package cn.modfun.common.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUtils {

	private static FtpUtils instance;
	
	private FTPClient ftpClient = null;
	
	public synchronized static FtpUtils getInstance(){  
        if( instance == null ){  
            instance = new FtpUtils();  
        }  
        return instance;  
    }
	/**
	 * 登录
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 */
	public void login(String ip,int port,String username,String password){
		ftpClient = new FTPClient();
		try{
			//连接  
            ftpClient.connect(ip, port);
            ftpClient.login(username,password);
            //检测连接是否成功  
            int reply = ftpClient.getReplyCode();  
            if(!FTPReply.isPositiveCompletion(reply)) {  
                this.close();  
                System.err.println(ftpClient.getReplyString());  
                System.exit(1);  
            } 
		}catch(Exception e){
			e.printStackTrace();
			this.close();
		}
	}
	
	/**
	 * 删除
	 * @param targetFile
	 * @return
	 */
	public boolean delete(String targetFile){  
        boolean flag = false;  
        if( ftpClient!=null ){  
        	try {
        		ftpClient.changeWorkingDirectory("");  
            	flag = ftpClient.deleteFile(targetFile);
			} catch (Exception e) {
				// TODO: handle exception
				this.close();
			}
//            try { 
//            	System.out.println(targetFile);
//                flag = ftpClient.deleteFile(targetFile);  
//            } catch (IOException e) {  
//                e.printStackTrace();  
//                this.close();  
//            }  
        }  
        return flag;  
    }
	public void batchDownload(String remoteDirectory,String localDirectory){
		batchDownload(remoteDirectory,localDirectory,true);
	}
	/**
	 * 批量下载
	 * @param remoteDirectory
	 * @param localDirectory
	 * @param limit
	 */
	public void batchDownload(String remoteDirectory,String localDirectory,boolean delete){
		/**/
		if(ftpClient != null){
			try{
				ftpClient.changeWorkingDirectory(remoteDirectory);
				ftpClient.enterLocalPassiveMode();  
				FTPFile[] fs = ftpClient.listFiles();
				if(fs.length >0){
					for(FTPFile ff:fs){
						File localFile = new File(localDirectory+"/"+ff.getName());  
		                OutputStream is = new FileOutputStream(localFile);   
		                ftpClient.retrieveFile(ff.getName(), is);  
		                is.close();
		                if(delete){
		                	ftpClient.deleteFile(ff.getName());
		                }
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	public boolean download(String remoteDirectory,String fileName,String localDirectory) {  
	    
		boolean flag = false;
		
		if(ftpClient != null){
			try{
				ftpClient.changeWorkingDirectory(remoteDirectory);
				FTPFile[] fs = ftpClient.listFiles();
				for(FTPFile ff:fs){  
		            if(ff.getName().equals(fileName)){  
		                File localFile = new File(localDirectory+"/"+ff.getName());  
		                OutputStream is = new FileOutputStream(localFile);   
		                ftpClient.retrieveFile(ff.getName(), is);  
		                is.close();  
		                return true;
		            }  
		        }
			}catch (Exception e) {  
                e.printStackTrace();  
                this.close();  
            }
		}
	    return flag;  
	}
	
	/**
	 * 上传（根目录）
	 * @param sourcePath
	 * @param targetFile
	 * @return
	 */
	public boolean upload(String sourcePath,String targetFile){
        return upload(sourcePath,null,targetFile); 
	}
	
	/**
	 * 上传
	 * @param sourcePath
	 * @param targetDirectory
	 * @param targetFile
	 * @return
	 */
	public boolean upload(String sourcePath,String targetDirectory,String targetFile){
		boolean flag = false;  
        if( ftpClient!=null ){  
             File srcFile = new File(sourcePath);   
             FileInputStream fis = null;  
             try {  
                fis  = new FileInputStream(srcFile);  
                  
                //设置上传目录   
                ftpClient.changeWorkingDirectory(targetDirectory == null?"/":targetDirectory);  
                ftpClient.setBufferSize(1024);   
                ftpClient.setControlEncoding("UTF-8");   
                  
                //设置文件类型（二进制）   
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
                //上传  
                flag = ftpClient.storeFile(targetFile, fis);   
            } catch (Exception e) {  
                e.printStackTrace();  
                this.close();  
            }finally{  
                IOUtils.closeQuietly(fis);  
            }  
        }  
        return flag; 
	}
	
	/**
	 * 关闭
	 */
	public void close(){  
        if(ftpClient !=null){  
            if(ftpClient.isConnected()){  
                try {  
                    ftpClient.logout();  
                    ftpClient.disconnect();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }   
            }  
        }  
    }
	public static void main(String[] args) {  
		FtpUtils.getInstance().login("192.168.118.77",21, "ftp", "123123");  
//        boolean flag = FtpUtils.getInstance().upload("D:\\ip.datx", "ip.datx");  
//        flag = FtpUtils.getInstance().download("/", "ip.datx", "v://");
        try {
        	FtpUtils.getInstance().ftpClient.dele("a.txt");
			System.out.println("flag:"+FtpUtils.getInstance().ftpClient.getReplyString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        //FtpConManager.getInstance().closeCon();  
  
    }
}